package com.hengxinguotong.zhihuichengjian.ui.device;

import android.Manifest;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.AualityTestAddPicAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Device;
import com.hengxinguotong.zhihuichengjian.bean.DeviceListRes;
import com.hengxinguotong.zhihuichengjian.picturebrowser.view.TaskBigImgActivity;
import com.hengxinguotong.zhihuichengjian.sys.CaptureActivity;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.ui.ScanningActivity;
import com.hengxinguotong.zhihuichengjian.utils.FileUtil;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.lidroid.xutils.http.RequestParams;
import com.orhanobut.logger.Logger;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * 设备巡检
 * Created by liux on 2017/3/13.
 */

public class DeviceInspectionActivity extends BaseActivity implements AualityTestAddPicAdapter.OnRecyclerViewClickListener {
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.save_tv)
    HXTextView saveTv;
    @BindView(R.id.select_ll)
    LinearLayout selectLl;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.scan_iv)
    ImageView scanIv;
    @BindView(R.id.name_etv)
    HXEditTextView nameEtv;
    @BindView(R.id.number_etv)
    HXEditTextView numberEtv;
    @BindView(R.id.position_rl)
    RelativeLayout positionRl;
    @BindView(R.id.model_etv)
    HXEditTextView modelEtv;
    @BindView(R.id.profession_rl)
    RelativeLayout professionRl;
    @BindView(R.id.manufactor_etv)
    HXEditTextView manufactorEtv;
    @BindView(R.id.no_pic_tv)
    HXTextView noPicTv;
    @BindView(R.id.add_pic_rv)
    RecyclerView addPicRv;
    @BindView(R.id.remarks_etv)
    HXEditTextView remarksEtv;
    @BindView(R.id.location_tv)
    HXTextView locationTv;
    @BindView(R.id.pass)
    RadioButton pass;
    @BindView(R.id.notpass)
    RadioButton notpass;
    @BindView(R.id.result_rg)
    RadioGroup resultRg;
    @BindView(R.id.result_ll)
    LinearLayout resultLl;
    @BindView(R.id.location_iv)
    ImageView locationIv;
    @BindView(R.id.leasing_company)
    HXTextView leasingCompany;
    private Device device;
    private int year = 0;
    private int monthOfYear = 0;
    private int dayOfMonth = 0;
    private List<String> paths;
    private List<String> minPaths;
    private String deviceId;  //设备id  扫描时获得
    private AualityTestAddPicAdapter addPicAdapter;
    private final int GETCODE = 1002;
    private final int GETDEVICE = 1003;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new MyAMapLocationListener();
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    private String longitude;
    private String latitude;
    private String address;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inspection);
        ButterKnife.bind(this);
        device = (Device) getIntent().getSerializableExtra("device");
        initView();
    }

    private void initView() {
        Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        monthOfYear = c.get(Calendar.MONTH);
        dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        paths = new ArrayList<String>();
        paths.add(Utils.ADDPIC);
        addPicAdapter = new AualityTestAddPicAdapter(this, paths, this, true);
        addPicRv.setLayoutManager(linearLayoutManager);
        addPicRv.setAdapter(addPicAdapter);
        if (device != null) {
            selectLl.setVisibility(View.GONE);
            scanIv.setVisibility(View.GONE);
            saveTv.setVisibility(View.GONE);
            Utils.setEditTextViewUnable(device.getName(), nameEtv);
            Utils.setEditTextViewUnable(device.getNumber(), numberEtv);
            Utils.setEditTextViewUnable(device.getModel(), modelEtv);
            Utils.setEditTextViewUnable(device.getManufacturer(), manufactorEtv);
            Utils.setEditTextViewUnable(device.getRemark(), remarksEtv);
            Utils.setEditTextViewUnable(device.getLeasingCompany(), leasingCompany);
            Utils.setEditTextViewUnable(device.getCurrentLocation(), locationTv);
            if ("1".equals(device.getResults())) {
                resultRg.check(R.id.pass);
            } else {
                resultRg.check(R.id.notpass);
            }
            Utils.disableRadioGroup(resultRg);

            paths = device.getPicList();
            if (paths.size() == 0) {
                noPicTv.setVisibility(View.VISIBLE);
                addPicRv.setVisibility(View.GONE);
            } else {
                addPicAdapter = new AualityTestAddPicAdapter(this, paths, this, false);
                addPicRv.setAdapter(addPicAdapter);
            }

            remarksEtv.setText(device.getRemark());
            remarksEtv.setEnabled(false);
        } else {
            init();
        }
    }


    private void init() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        }
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(false);

        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();

    }


    private class MyAMapLocationListener implements AMapLocationListener {

        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    longitude = aMapLocation.getLongitude() + "";
                    latitude = aMapLocation.getLatitude() + "";
                    address = aMapLocation.getPoiName();
                    locationTv.setText(address);
                } else {
                    showToast("定位失败,请打开网络以及gps定位");
                    locationTv.setText("定位失败");
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Logger.d(" ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                }
            }
        }
    }

    @OnClick({R.id.iv_back, R.id.save_tv, R.id.scan_rl, R.id.list_rl})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.save_tv:
                getMinImage();
                break;
            case R.id.scan_rl:
                intent = new Intent(this, ScanningActivity.class);
                startActivityForResult(intent, GETCODE);
                break;
            case R.id.list_rl:
                intent = new Intent(this, DeviceSelectedActivity.class);
                startActivityForResult(intent, GETDEVICE);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data != null){
            if (requestCode == 1) {
                paths = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                paths.add(Utils.ADDPIC);
                if (addPicAdapter != null) {
                    addPicAdapter.setPaths(paths);
                }
            } else if (requestCode == GETCODE) {
                String code = data.getStringExtra("QRcode");
//            if (code.contains("_")) {
//                deviceId = code.split("_")[1];
//                getDeviceInfo(getResources().getString(R.string.loading));
//            }
                if(code.contains("_")){
                    deviceId = code.split("_")[1];
                }else{
                    deviceId = code;
                }
                numberEtv.setText(code);
                getDeviceInfo(getResources().getString(R.string.loading));
            } else if (requestCode == GETDEVICE) {
                device = (Device) data.getExtras().get("device");
                deviceId = device.getId();
                reloadViews(device);
            }
        }
    }

    @Override
    public void onItemClick(View v, int position) {
        Intent intent;
        if (paths.get(position).equals(Utils.ADDPIC)) {
            List<String> tempStrings = new ArrayList<String>();
            tempStrings.addAll(paths);
            tempStrings.remove(tempStrings.size() - 1);
            MultiImageSelector.create()
                    .showCamera(true) // show camera or not. true by default_grey
                    .count(9) // max select image size, 9 by default_grey. used width #.multi()
                    .multi()
                    .origin((ArrayList<String>) tempStrings)
                    .start(this, 1);
        } else {
            if (device != null) {
                TaskBigImgActivity.startActivity(this, (ArrayList<String>) paths, position);
            } else {
                paths.remove(position);
                addPicAdapter.notifyDataSetChanged();
            }
        }
    }

    private void getDeviceInfo(String alert) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("equipmentId", deviceId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/equipmentRegister/queryList/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    DeviceListRes deviceListRes = gson.fromJson(json, DeviceListRes.class);
                    if (deviceListRes.getValue().size() == 1) {
                        reloadViews(deviceListRes.getValue().get(0));
                    }
                }

            }

            @Override
            public void onFailure(String json) {

            }
        });
    }


    private boolean checkText() {
        if (Utils.isEmpty(deviceId)) {
            showToast("请扫描机器上的二维码或选择设备列表");
            return false;
        }


        if (resultRg.getCheckedRadioButtonId() == -1) {
            showToast("请选择处理结果");
            return false;
        }

        return true;
    }


    public void getMinImage() {
        if (!checkText()) {
            return;
        }

        if (paths.size() > 1) {
            Utils.startDownload(getResources().getString(R.string.loading), this);

            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    minPaths = new ArrayList<String>();
                    for (int i = 0; i < paths.size() - 1; i++) {
                        String path = FileUtil.imageDir1 + System.currentTimeMillis() + ".jpg";
                        FileUtil.writeByteArrayToPath(path, FileUtil.handleUploadImg(paths.get(i)));
                        minPaths.add(path);
                    }
                    return null;
                }


                @Override
                protected void onPostExecute(Void aVoid) {
                    deviceInspection();
                }


            }.execute();
        } else {
            minPaths = new ArrayList<String>();
            deviceInspection();
        }

    }

    private void deviceInspection() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("equipmentId", deviceId);
        params.addBodyParameter("constructionId",  SPUtil.getString(this,"constructionid"));
        params.addBodyParameter("createBy", SPUtil.getString(this, "userId"));
        params.addBodyParameter("remark", remarksEtv.getEditableText().toString());
        if (resultRg.getCheckedRadioButtonId() == R.id.pass) {
            params.addBodyParameter("results", "1");
        } else {
            params.addBodyParameter("results", "2");
        }
        if (address != null) {
            params.addBodyParameter("currentLocation", address);
            params.addBodyParameter("longitude", longitude);
            params.addBodyParameter("latitude", latitude);
        }

        for (int i = 0; i < minPaths.size(); i++) {
            params.addBodyParameter("files[" + i + "]", new File(minPaths.get(i)));
        }


        Utils.requestData(getResources().getString(R.string.loading), DeviceInspectionActivity.this, "/equipmentRegister/insertInspection/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    DeviceInspectionActivity.this.showToast("提交成功");
                    setResult(1);
                    finish();
                }
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }


    private void reloadViews(Device device) {
        nameEtv.setText(device.getName());
        numberEtv.setText(device.getNumber());
        modelEtv.setText(device.getModel());
        manufactorEtv.setText(device.getManufacturer());
        leasingCompany.setText(device.getLeasingCompany());
    }
}
